<template>
  <a-modal width="640px" :title="type === 1 ? '达人探店费用请款' : '达人探店费用请款详情'" :visible="value" :maskClosable="false" @cancel="onCancel">
    <a-spin tip="提交中..." :spinning="isSubLoading">
      <a-form-model ref="applyModalForm" :model="applyModalForm" :rules="applyRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-model-item label="请款类型" prop="value1">
          <a-radio-group v-model="applyModalForm.value1" :disabled="type === 2" @change="onChangeValue1">
            <a-radio :value="1">
              CPS+一口价
            </a-radio>
            <a-radio :value="2">
              一口价
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="请款阶段" prop="value2" v-if="applyModalForm.value1 === 2">
          <a-radio-group v-model="applyModalForm.value2" :disabled="type === 2" @change="onChange">
            <a-radio :value="1">
              首款
            </a-radio>
            <a-radio :value="2">
              尾款
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="ID绑定" v-if="applyModalForm.value2 === 1" prop="productIdAndDyNoList">
          <div v-for="(item, index) in applyModalForm.productIdAndDyNoList" :key="index">
            <a-input v-model="item.productId" :disabled="type === 2" type="number" placeholder="产品ID" :max-length="20" style="width: 150px" />
            ---
            <a-input v-model="item.dyNo" :disabled="type === 2" v-on:keyup="checkDyNumber($event)" placeholder="抖音号" :max-length="15" style="width: 150px" />
            &nbsp;&nbsp;
            <a-button type="primary" @click="dealIds('add', index)" shape="circle" size="small" icon="plus" v-if="index === 0 && type === 1" />
            <a-button type="primary" @click="dealIds('del', index)" shape="circle" size="small" icon="minus" v-else-if="type === 1" />
          </div>
        </a-form-model-item>
        <a-form-model-item label="请款金额" v-if="applyModalForm.value2" prop="money">
          <a-input v-model="applyModalForm.money" :disabled="type === 2" style="width:240px;" placeholder="请输入请款金额"></a-input>
        </a-form-model-item>
        <a-form-model-item label="业务经办人" prop="businessUserId">
          <a-select
            @search="getAllUserFun"
            :disabled="type === 2"
            v-model="applyModalForm.businessUserId"
            :showArrow="false"
            style="width:240px;"
            show-search
            :filter-option="false"
            allow-clear
            placeholder="请输入姓名/工号搜索"
          >
            <a-spin v-if="userLoading" slot="notFoundContent" size="small" />
            <a-select-option v-for="(item, index) in allUser" :key="index" :value="item.userId">{{ item.userName }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="达人申请个数" prop="applyNum">
          <a-input v-model="applyModalForm.applyNum" :disabled="type === 2" style="width:240px;" placeholder="请输入达人申请个数"></a-input>
        </a-form-model-item>
        <a-form-model-item label="申请原因" prop="applyReason">
          <a-input v-model="applyModalForm.applyReason" :disabled="type === 2" type="textarea" placeholder="请输入申请原因"></a-input>
        </a-form-model-item>
        <a-form-model-item label="合同" prop="contactUrl">
          <upload :limit="9" v-model="applyModalForm.contactUrl" v-if="type === 1"></upload>
          <upload :limit="applyModalForm.contactUrl.length || 0" :disabled="true" v-else :value="applyModalForm.contactUrl"></upload>
          <div class="image-remind upload1" v-if="type === 1">注：所有需打款达人的电子合同截图</div>
        </a-form-model-item>
        <a-form-model-item label="其他格式附件" prop="attachment">
          <upload :limit="9" v-if="type === 1" type="file" accept=".pdf,.doc,.xls" v-model="applyModalForm.attachment"></upload>
          <upload :limit="applyModalForm.attachment.length || 0" v-else :disabled="true" type="file" accept=".pdf,.doc,.xls" :value="applyModalForm.attachment"></upload>
          <div class="image-remind upload2" v-if="type === 1">注：今日达人费用报销单，支持pdf、doc、xls</div>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
    <!-- 操作 -->
    <template slot="footer">
      <template style="display:flex;justify-content: center;">
        <a-button @click="onCancel">关闭</a-button>
        <a-button v-show="type === 1" type="primary" style="background:#1D6FE9" @click="submitApply">提交申请</a-button>
      </template>
    </template>
  </a-modal>
</template>
<script>
import upload from '@/components/upload/upload'
import { getAllUserList, agentShopApply } from '@/service'
import debounce from 'lodash/debounce'
const g = function(row = {}) {
  return {
    value1: row.value1 || 1,
    money: row.money ? (row.money / 100).toFixed(2) : '',
    contactUrl: row.contactUrl || [],
    attachment: row.attachment || [],
    applyReason: row.applyReason || '',
    applyNum: row.applyNum || '',
    value2: row.value2 || '',
    productIdAndDyNoList: row.productIdAndDyNoList || [{ dyNo: '', productId: '' }],
    businessUserId: row.businessUserId ? String(row.businessUserId) : undefined
  }
}
export default {
  name: 'applyForm',
  props: {
    type: {
      type: Number,
      default: 0
    },
    value: {
      type: Boolean,
      default: false
    },
    getInfo: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    getInfo(val) {
      if (val && Object.keys(val).length > 0) {
        this.applyModalForm = g(val)
        const { costType = '', businessUserName = '' } = val || {}
        if (costType === 0) {
          this.applyModalForm.value1 = 1
        } else if (costType === 1) {
          this.applyModalForm.value1 = 2
          this.applyModalForm.value2 = 1
        } else if (costType === 2) {
          this.applyModalForm.value1 = 2
          this.applyModalForm.value2 = 2
        }
        this.applyModalForm.businessUserId = businessUserName
      }
    }
  },
  components: { upload },
  data() {
    let checkMoney = (rule, value, callback) => {
      var pattern = /^\d+(\.\d+)?$/
      if (!value) {
        callback(new Error('请输入金额'))
      } else if (!pattern.test(value) && value) {
        callback(new Error('金额格式有误'))
      } else {
        callback()
      }
    }
    let checkIds = (rule, value, callback) => {
      callback()
    }
    this.getAllUserFun = debounce(this.getAllUserFun, 800)
    return {
      userLoading: false,
      allUser: [],
      applyModalForm: g(),
      isSubLoading: false,
      warningShow: false,
      applyRules: {
        value1: [{ required: true, message: '请选择请款类型', trigger: 'blur' }],
        value2: [{ required: true, message: '请选择请款阶段', trigger: 'blur' }],
        productIdAndDyNoList: [
          {
            validator: checkIds,
            required: true,
            message: '请按提示输入ID绑定',
            trigger: 'change'
          }
        ],
        applyReason: [
          { required: true, message: '请输入申请原因', trigger: 'blur' },
          { min: 0, max: 200, message: '最长不超过200字', trigger: 'blur' }
        ],
        businessUserId: [{ required: true, message: '请选择业务经办人', trigger: 'blur' }],
        contactUrl: [{ required: true, message: '请上传合同', trigger: 'blur' }],
        attachment: [{ required: true, message: '请上传其他格式附件', trigger: 'blur' }],
        applyNum: [
          { required: true, message: '请输入达人申请个数', trigger: 'blur' },
          { min: 0, max: 10, message: '最长不超过10位', trigger: 'blur' },
          {
            pattern: /^[0-9]*$/,
            message: '达人申请个数格式有误',
            trigger: 'blur'
          }
        ],
        money: [
          {
            validator: checkMoney,
            required: true,
            message: '请输入金额',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    getAllUserFun(keywords) {
      return new Promise((resolve, reject) => {
        keywords = keywords.replace(/ /g, '')
        // if (!keywords) return reject(new Error('process'))
        this.userLoading = true
        getAllUserList({ keywords })
          .then((res = {}) => {
            const { records = [] } = res
            this.allUser = records
            resolve(res)
          })
          .catch(() => {
            return reject(new Error('接口出错'))
          })
          .finally(() => {
            this.userLoading = false
          })
      })
    },
    onCancel() {
      this.$emit('input', false)
      this.applyModalForm = g({})
      this.clearForm()
    },
    checkDyNumber(e) {
      const { value = '' } = e.target || {}
      if (!/^[a-zA-Z0-9_]*$/.test(value)) {
        event.target.value = value.replace(/[\W]/g, '')
      }
    },
    clearForm() {
      let form = this.$refs.applyModalForm
      if (form && form.clearValidate) {
        this.$nextTick(() => {
          form.clearValidate()
        })
      }
    },
    onChange() {},
    onChangeValue1(e) {
      this.applyModalForm.value2 = null
      this.applyModalForm.productIdAndDyNoList = [{ dyNo: '', productId: '' }]
      this.clearForm()
    },
    // 增删id绑定
    dealIds(type = '', index) {
      let addObj = { dyNo: '', productId: '' }
      if (type === 'add') {
        this.applyModalForm.productIdAndDyNoList.push(addObj)
      } else if (type === 'del') {
        this.applyModalForm.productIdAndDyNoList.splice(index, 1)
      }
    },
    submitApply() {
      this.$refs.applyModalForm.validate((valid, obj = {}) => {
        if (valid) {
          const { value2 = '', value1, money = '', contactUrl = [], attachment = [], applyReason = '', applyNum = '', productIdAndDyNoList = [], businessUserId = '' } = this.applyModalForm || {}
          if (value2 === 1 && productIdAndDyNoList.length === 0) {
            this.$messageSend.error('请至少填写一例ID绑定')
            return
          }
          if (productIdAndDyNoList.length >= 1 && value2 === 1) {
            if (!(productIdAndDyNoList[0].dyNo && productIdAndDyNoList[0].productId)) {
              this.$messageSend.error('请完整输入第一条ID绑定')
              return
            }
          }
          let compCostType = ''
          if (value1 === 1) {
            compCostType = 0
          } else if (value1 === 2) {
            if (value2 === 1) {
              compCostType = 1
            } else if (value2 === 2) {
              compCostType = 2
            }
          }
          const postParams = { costType: compCostType, money: money ? money * 100 : 0, contactUrl, attachment, applyReason, applyNum, productIdAndDyNoList, businessUserId }
          this.isSubLoading = true
          agentShopApply(postParams)
            .then((res) => {
              this.$emit('callback')
              this.onCancel()
            })
            .finally(() => {
              this.isSubLoading = false
            })
            .catch(() => {
              this.isSubLoading = false
            })
        }
      })
    }
  }
}
</script>
<style scoped>
.image-remind {
  color: #666;
  font-size: 12px;
  height: 20px;
  margin-top: -15px;
}
.upload1 {
  position: relative;
  top: -10px;
}
.upload2 {
  margin-top: 0;
  position: relative;
  top: -10px;
}
</style>
